package com.tan.websocket.handler;

import com.alibaba.fastjson.JSON;
import com.tan.common.domain.chat.ChatGroupUser;
import com.tan.common.dto.chat.ChatInfoDTO;
import com.tan.common.enums.MessageTypeEnum;
import com.tan.websocket.event.ChatGroupMember;
import com.tan.websocket.event.ChatPublisher;
import com.tan.websocket.service.IChatGroupUserService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.tan.websocket.config.WebsocketAuthHandler.channelMap;


/**
 * @author Tan
 * @description 根据消息类型推送消息
 * @date 2025/1/28
 */
@Slf4j
@Component
public class ChatBaseHandle {

    @Resource
    private IChatGroupUserService chatGroupUserService;

    public void handle(ChatInfoDTO chatInfo) {
        if (MessageTypeEnum.GROUP_CHAT.eq(chatInfo.getMessageType())) {
            this.handleGroupMsg(chatInfo);
        }
        if (MessageTypeEnum.PRIVATE_CHAT.eq(chatInfo.getMessageType())) {
            Channel receiver = channelMap.get(chatInfo.getReceiver().toString());
            if (receiver != null && receiver.isOpen() && receiver.isActive()) {
                this.handlePrivateMsg(receiver, chatInfo);
            }
        }


    }

    /***
     * @author Tan-Bowen
     * @description 处理私聊消息
     * @date 2025/1/29 0:29
     * @param [channel, chatInfo]
     */
    public void handlePrivateMsg(Channel channel, ChatInfoDTO chatInfo) {
        // 私聊消息处理
        String content = JSON.toJSONString(chatInfo);
        channel.writeAndFlush(new TextWebSocketFrame(content));
    }

    /***
     * @author Tan-Bowen
     * @description 处理群发消息
     * @date 2025/1/29 0:29
     * @param [chatInfo]
     */
    public void handleGroupMsg(ChatInfoDTO chatInfo) {
        // 获取群人员
        Long receiver = chatInfo.getReceiver();
        List<ChatGroupUser> groupUsers = chatGroupUserService.groupUsers(receiver);
        ChatPublisher publisher = new ChatPublisher();
        groupUsers.forEach(item -> {
            Channel receiverChannel = channelMap.get(item.getUserId().toString());
            publisher.registerListener(ChatInfoDTO.class,ChatGroupMember.builder()
                    .channel(receiverChannel)
                    .build());
        });
        publisher.sendMessage(chatInfo);
    }


}
